﻿using CsvHelper;
using PerfTestLib.Runtime;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace PerfTestLib.Utility
{
    public static class CsvExtensions
    {
        public static void WriteCsv(this DataTable table, string specId, string iterationId, int index)
        {
            string path = TestFileUtility.GetTestSpecIterationOutputFileLocation(specId, iterationId, index, DateTime.Now, true);

            WriteCsv(table, path);
        }

        public static void WriteCsv(this DataTable table, string path)
        {
            if (table == null)
                return;

            // create CSV file
            using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write))
            {
                // text writer
                using (StreamWriter sw = new StreamWriter(fs))
                {
                    // CSV writer
                    using (CsvWriter writer = new CsvWriter(sw))
                    {
                        // write columns
                        foreach (DataColumn col in table.Columns)
                        {
                            writer.WriteField(col.ColumnName);
                        }

                        writer.NextRecord();

                        // write each row
                        foreach (DataRow row in table.Rows)
                        {
                            foreach (DataColumn col in table.Columns)
                            {
                                var data = row[col.ColumnName];

                                writer.WriteField(data);
                            }

                            writer.NextRecord();
                        }
                    }
                }
            }
        }
    }
}
